import { createRouter, createWebHashHistory } from 'vue-router';
import type * as VueRouter from 'vue-router';
import _ from 'lodash';

import ThirdPlatformSession from '@core/engine/ThirdPlatform/Session';
import exceptionRoutes from '@core/views/exception/routes';
import EnvConfig from './EnvConfig';
import HistoryHelper from './HistoryHelper';

export const ROOT_ROUTE_NAME = 'root';

// TODO: 添加路由鉴权逻辑
const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/:pathMatch(.*)*', redirect: '/exception/404',
    },
  ],
});

router.beforeEach((to) => {
  return authCheckMiddleware(to);
});

export interface RouteModule {
  default: VueRouter.RouteRecordRaw;
}

const migrateMetaToProps = (routeRecord: VueRouter.RouteRecordRaw): VueRouter.RouteRecordRaw => {
  const mergedRoute = routeRecord;
  const props = typeof routeRecord.props === 'boolean' ? {} : routeRecord.props;
  const mergedProps = { ...props, fromMeta: routeRecord.meta };
  if (!_.isEmpty(mergedProps)) {
    mergedRoute.props = mergedProps;
  }
  if (!_.isEmpty(routeRecord.children)) {
    mergedRoute.children = mergedRoute.children?.map(migrateMetaToProps);
  }
  return mergedRoute;
};

export const buildSubAppViewRoutes = (viewRouteModules: Record<string, RouteModule>) => {
  const viewRoutes: VueRouter.RouteRecordRaw[] = [];
  for (const modulePath of Object.keys(viewRouteModules)) {
    viewRoutes.push(migrateMetaToProps(viewRouteModules[modulePath].default));
  }
  viewRoutes.push(getSubAppExceptionRoutes());
  return viewRoutes;
};

export const authCheckMiddleware = (to: VueRouter.RouteLocationNormalized) => {
  if (EnvConfig.isConnectToPublicPlatform()) {
    return true;
  }
  // 连接第三方平台时，需要检查 cookie 中缓存的 auth token，没有 token 的话跳转到登录页
  const authToken = ThirdPlatformSession.getAuthToken();
  if (to.name !== 'login' && authToken === undefined) {
    HistoryHelper.replaceToLogin();
    return false;
  }
  return true;
};

export const getSubAppExceptionRoutes = () => {
  return exceptionRoutes;
};

export default router;
